package org.current;

import org.junit.Test;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 异步操作相关测试
 *
 * @author LiKun
 * @date 2021/11/24 20:02
 */
public class AsyncOperate {

    // 默认的线程池
    private final ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 验证 {@link ExecutorService#submit(Callable)} 方法的使用
     *
     * @throws Exception 异常信息
     */
    @Test
    public void verifyExecutorServiceSubmit() throws Exception {
        final int times = 25;
        final List<Future<LocalDateTime>> futures = new ArrayList<>();

        final long millis = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            futures.add(Executors.newFixedThreadPool(times).submit(() -> {
                try {
                    final long time = ThreadLocalRandom.current().nextLong(10000);
                    System.out.println("随机数为: " + time);
                    Thread.sleep(time);
                } catch (InterruptedException exception) {
                    System.out.println("线程休眠出现异常");
                }
                return LocalDateTime.now();
            }));
        }
        System.out.println("总耗时: " + (System.currentTimeMillis() - millis));
    }

    /**
     * 验证 {@link CountDownLatch} 的线程同步功能
     *
     * @throws Exception 异常信息
     */
    @Test
    public void verityCountDownLatch() throws Exception {
        final int times = 25;
        final List<Future<LocalDateTime>> futures = new ArrayList<>();
        final CountDownLatch countDownLatch = new CountDownLatch(times);

        final long millis = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            futures.add(Executors.newFixedThreadPool(times).submit(() -> {
                try {
                    final long time = ThreadLocalRandom.current().nextLong(10000);
                    System.out.println("随机数为: " + time);
                    Thread.sleep(time);
                } catch (InterruptedException exception) {
                    System.out.println("线程休眠出现异常");
                } finally {
                    countDownLatch.countDown(); // 计数器减一
                    countDownLatch.await(); // 等待其他线程完成任务

                    System.out.println(System.currentTimeMillis()); // 输出时间以证明是否同步
                }
                return LocalDateTime.now();
            }));
        }
        countDownLatch.await(); // 等待全部的异步线程执行完成
        System.out.println("总耗时: " + (System.currentTimeMillis() - millis));
    }

}
